<?php

!defined('BASE_PATH')&&die('forbidden');

class core_route_routerbase{
	
	public static $action = null;
	
	public static $method = null;
	
	public static $args = array();

	//fix the bug at https://bugs.php.net/bug.php?id=38143
	public static function _parse_url($url) {

		$arr = explode('?',$url);
		$prefix = array_shift($arr);
		$tail = implode('?',$arr);
		
		$arr = parse_url($prefix);
		if($tail){
			if(false!==strpos($tail,'#')){
				$arr['query'] = substr($tail,0,strpos($tail,'#'));
				$arr['fragment'] = substr($tail,strpos($tail,'#')+1);
			}else{
				$arr['query'] = $tail;
			}
		}
		
		return $arr;
	}
		
	public static function route($request_uri){
		
		$slice = parse_url($request_uri);
		unset($request_uri);
		
		self::_parse_path($slice['path']);
		
		if (!self::$action) {
			self::$action = isset($_GET['c']) ? $_GET['c'] : 'welcome';
		}
		
		if (!self::$method) {
			self::$method = isset($_GET['m']) ? $_GET['m'] : 'index';
		}
		
		if (!self::$args) {
			self::$args = isset($_GET['args']) ? (array)$_GET['args'] : array();
		}
		
	}
	
	public static function get_action(){
		
		return self::$action;
		
	}
	
	public static function get_method(){
		
		return self::$method;
		
	}
	
	public static function get_args(){
		
		return self::$args;
		
	}
	
	private static function _parse_path($path){

		$slice = array_filter(explode('/' , trim($path , '/')));
		unset($path);
		
		if (sizeof($slice) > 0) {
			self::$action = array_shift($slice);
		}
		
		if (sizeof($slice) > 0) {
			self::$method = array_shift($slice);
		}
		
		if (sizeof($slice) > 0) {
			self::$args = $slice;
		}
		
	}
	
	public static function build_uri($action,$method,$args,$query_string){
		
		return BASE_URI . implode('/',array($action,$method,implode('/',$args))) . '?' . $query_string;
		
	}
	
}

?>